import aiofiles
from typing import Annotated

from fastapi import APIRouter, File, Depends, UploadFile
from sqlalchemy import select
from sqlalchemy.orm import selectinload

from db.db import AsyncSession, get_session
from utils.write_to_db import write_doctors_info_to_db
from models.models import User
from routers.users import oauth2_scheme

doctors_router = APIRouter()


@doctors_router.post("/uploadfile/")
async def upload_file(
    token: Annotated[str, Depends(oauth2_scheme)],
    file: UploadFile = File(...),
    session: AsyncSession = Depends(get_session),
):
    """Загружает файл с данными о врачах."""

    filename = file.filename
    async with aiofiles.open(f"download/{filename}", mode="wb") as buffer:
        contents = await file.read()
        await buffer.write(contents)
    await write_doctors_info_to_db(filename=filename, session=session)
    return {"msg": "Файл успешно загружен"}


@doctors_router.get("/doctors_info")
async def get_doctors_info(
    token: Annotated[str, Depends(oauth2_scheme)],
    session: AsyncSession = Depends(get_session),
    limit: int = None,
    offset: int = 0,
):
    """Возвращает данные о врачах."""
    query = (
        select(User)
        .options(
            selectinload(User.modality),
            selectinload(User.additional_modalities),
        )
        .where(
            User.role_id == 4,
            User.modality != None,
        )
    ).limit(limit).offset(offset)
    query_result = await session.execute(query)
    return [
        {
            "id": user.id,
            "name": user.username,
            "modality": user.modality.name or None,
            "additional_modality": [user.modality.name for user.modality in user.additional_modalities],
        }
        for user in query_result.scalars().all()
    ]
